package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.Constant;
import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.bean.usertag.CreateUserTagBean;
import com.adouteam.simple.wechat.bean.usertag.CreateUserTagResultBean;
import com.adouteam.simple.wechat.bean.usertag.UserTag;
import com.adouteam.simple.wechat.bean.usertag.UserTags;
import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class UserTagService{
    private static Logger logger = LoggerFactory.getLogger(UserTagService.class);

    private static int MAX_LENGTH_OF_USER_TAG_NAME = 30;

    public static UserTags getAllUserTags(WechatConstants wechatConstants){
        String url = WeixinUrls.replace(WeixinUrls.USER_TAG_GET_LIST_URL, wechatConstants, null);
        return HttpUtil.get(url, null, (httpResponse) ->
                JSONObject.parseObject(EntityUtils.toString(httpResponse.getEntity(), "utf-8"), UserTags.class)
        );
    }

    public static CreateUserTagResultBean createUserTag(String nameOfNewUserTag, WechatConstants wechatConstants){
        if(StringUtils.isBlank(nameOfNewUserTag)){
            return null;
        }
        if(StringUtils.length(nameOfNewUserTag) > MAX_LENGTH_OF_USER_TAG_NAME){
            nameOfNewUserTag = StringUtils.substring(nameOfNewUserTag, 0, MAX_LENGTH_OF_USER_TAG_NAME - 1);
        }
        CreateUserTagBean createUserTagBean = new CreateUserTagBean();
        Map<String, String> tagMap = new HashMap<>(1);
        tagMap.put("name", nameOfNewUserTag);
        createUserTagBean.setTag(tagMap);
        String url = WeixinUrls.replace(WeixinUrls.USER_TAG_CREATE_URL, wechatConstants, null);
        String requestJsonBody = JSONObject.toJSONString(createUserTagBean);
        System.out.println(requestJsonBody);
        HttpEntity httpEntity = EntityBuilder.create()
                .setText(requestJsonBody)
                .setContentType(ContentType.APPLICATION_JSON)
                .build();
        return HttpUtil.post(url, null, httpEntity, (httpResponse -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            System.out.println(responseContent);
            CreateUserTagResultBean createUserTagResultBean = JSONObject.parseObject(responseContent, CreateUserTagResultBean.class);
            logger.debug(Constant.LOGGER_PREFIX + "create user tag result:" + createUserTagResultBean.toString());
            System.out.println(Constant.LOGGER_PREFIX + "create user tag result:" + createUserTagResultBean.toString());
            return createUserTagResultBean;
        }));
    }

    public static Boolean updateUserTag(int tagId, String newNameOfUserTag, WechatConstants wechatConstants){
        if(StringUtils.isBlank(newNameOfUserTag)){
            return false;
        }
        if(StringUtils.length(newNameOfUserTag) > MAX_LENGTH_OF_USER_TAG_NAME){
            newNameOfUserTag = StringUtils.substring(newNameOfUserTag, 0, MAX_LENGTH_OF_USER_TAG_NAME - 1);
        }
        UserTag userTag = new UserTag();
        userTag.setId(tagId);
        userTag.setName(newNameOfUserTag);
        Map<String, UserTag> userTagMap = new HashMap<>(1);
        userTagMap.put("tag", userTag);
        String url = WeixinUrls.replace(WeixinUrls.USER_TAG_UPDATE_URL, wechatConstants, null);
        String requestJsonBody = JSONObject.toJSONString(userTagMap);
        logger.debug(Constant.LOGGER_PREFIX + "update user tag request json body:" + requestJsonBody);
        HttpEntity httpEntity = EntityBuilder.create()
                .setText(requestJsonBody)
                .setContentType(ContentType.APPLICATION_JSON)
                .setContentEncoding("utf-8")
                .build();
        return HttpUtil.post(url, null, httpEntity, (httpResponse -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            if(StringUtils.isBlank(responseContent)){
                return false;
            }
            JSONObject jsonObject = JSONObject.parseObject(responseContent);
            if(null == jsonObject){
                return false;
            }
            if(jsonObject.containsKey("errcode") && jsonObject.getIntValue("errcode") == 0){
                return true;
            }
            return false;
        }));
    }
}
